package com.listeningframework.boot;

import com.listeningframework.boot.commons.http.HttpWebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 
 * Listening BootApplication
 *
 * @author lixining
 * @version $Id: BootApplication.java, v 0.1 2016年11月4日 上午10:36:58 lixining Exp $
 */
@SpringBootApplication(scanBasePackages = { BootApplication.LISTENING_BOOT, BootApplication.LISTENING_WORKS })
public class BootApplication extends SpringBootServletInitializer {
    /**
     * 日志
     */
    private static final Logger LOG             = LoggerFactory.getLogger(BootApplication.class);
    /**
     * Listening Ext Package
     */
    public static final String  LISTENING_BOOT  = "com.listeningframework";
    /**
     * Listening Works Package
     */
    public static final String LISTENING_WORKS = "${listening.works.package:com.listening.works}";

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(BootApplication.class);
    }

    /**
    * Boot Method
     *
     * @param args 入参
     * @throws Exception 启动异常
    */
    public static final void boot(String[] args) throws Exception {
        boot(BootApplication.class, args);
    }

    /**
     * Boot Method
     *
     * @param cls 启动类
     * @param args 启动参数
     */
    public static final void boot(Class<?> cls, String[] args) {
        ConfigurableApplicationContext app = SpringApplication.run(cls, args);
        Environment env = app.getEnvironment();
        String name = env.getProperty("spring.application.name");
        String port = env.getProperty("server.port");
        String context = env.getProperty("server.context-path");
        String ip = HttpWebUtils.getLocalIp();

        StringBuilder builder = new StringBuilder();
        builder.append("\n----------------------------------------------------------\n\t");
        builder.append("Application '{}' is running! Access URLs:\n\t");
        builder.append("Local: \t\thttp://127.0.0.1:{}{}\n\t");
        builder.append("External: \thttp://{}:{}");
        builder.append("\n----------------------------------------------------------");
        LOG.info(builder.toString(), name, port, context, ip, port);
    }
}
